package com.isa.androidwebtrans;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.net.URL;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.SecretKey;
import javax.net.ssl.HttpsURLConnection;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.RadioGroup;

import com.android.crypto.CryController;
import com.android.crypto.Crypto;
import com.isa.http.HttpAssist;
import com.isa.ssl.HTTPSCoder;
import com.isa.util.Arguments;
import com.isa.util.Myhandler;

@SuppressLint("NewApi")
public class ChooseKeyActivity extends ListActivity {

	private String[] keyTypes = new String[] { "RSA DES", "RSA AES" };
	public Myhandler handler = Myhandler.getInstance();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_expandable_list_item_1);
		addType(adapter);
		this.setListAdapter(adapter);
	}

	public void addType(ArrayAdapter adapter) {
		for (String str : keyTypes) {
			adapter.add(str);
		}
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		final String keyType = keyTypes[position];
		System.out.println(keyType);
		final View keyDialog = getLayoutInflater().inflate(R.layout.choosekey,
				null);
		new AlertDialog.Builder(ChooseKeyActivity.this).setTitle("请选择文件传输方式")
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						/*
						 * 1.提取keyType 2.调函数产生密钥(发送请求到服务器) 3.传递加密之后的密钥 4.设置flag
						 */
						RadioGroup rg = (RadioGroup) keyDialog
								.findViewById(R.id.rg);
						int rb = rg.getCheckedRadioButtonId();

						if (rb == R.id.SerToCli) {

						} else if (rb == R.id.CliToSer) {
							new Thread() {
								public void run() {
									try {
										String[] keys = keyType.split(" ");
										SecretKey sKey = Crypto
												.generateKey(keys[1]);
										byte[] wrapkey = getUploadPubKey(sKey,
												keys[0]);
										sendWrapKey(wrapkey, keys[1]);
//										HttpAssist.downLoad(
//												Arguments.WEB_DOWNLOAD
//														+ "?filename=1427541161778.jpg",
//												Arguments.ROOT_PATH
//														+ "/1427541161778.jpg");
										
										handler.sendEmptyMessage(Arguments.MESSAGE_UPLOADKEY_OK);
									} catch (Exception e) {
										e.printStackTrace();
										handler.sendEmptyMessage(Arguments.MESSAGE_UPLOADKEY_WRONG);
									}
								};
							}.start();

						}

					}
				}).setNegativeButton("取消", null).setView(keyDialog).show();
	}

	public void sendWrapKey(byte[] wrapkey, String keytype) throws Exception {

		URL realUrl = new URL(Arguments.WEB_KEY_CHANGE);
		HttpsURLConnection conn = (HttpsURLConnection) realUrl.openConnection();
		conn.setDoInput(true);
		conn.setRequestMethod("POST");
		conn.setRequestProperty("Content-Type",
				"application/x-www-form-urlencoded");
		HTTPSCoder.configSSLSocketFactory(conn);
		OutputStream os = conn.getOutputStream();
		os.write(wrapkey);
		os.close();

		if (conn.getResponseCode() == 200)
			System.out.println("OK!");
		else
			System.out.println("wrong");
		System.out.println("传输成功！");
		Arguments.IS_UPLOAD_KEY_CHANGED = 1;
	}

	public byte[] getUploadPubKey(SecretKey sKey, String type) throws Exception {
		// 分割对称加密和非对称加密
		System.out.println(type);
		URL realUrl = new URL(Arguments.WEB_KEY_CHANGE
				+ "?action=getpubkey&keytype=" + type);
		HttpsURLConnection conn = (HttpsURLConnection) realUrl.openConnection();
		conn.setDoInput(true);
		conn.setRequestMethod("GET");
		HTTPSCoder.configSSLSocketFactory(conn);
		InputStream is = conn.getInputStream();
		System.out.println(conn.getResponseCode());
		ObjectInputStream osi = new ObjectInputStream(conn.getInputStream());
		PublicKey puk = (PublicKey) osi.readObject();
		System.out.println(puk.getEncoded());
		// 获取打包之后的对称密钥
		byte[] wrapkey = CryController.wrapKey(sKey, puk);
		is.close();
		return wrapkey;

	}

}
